package com.dmc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dmc.conf.Constant;
import com.dmc.dict.BenefitTranTypeDict;
import com.dmc.dict.OrderStatusDict;
import com.dmc.dict.UserLevelDict;
import com.dmc.entity.Message;
import com.dmc.mapper.*;
import com.dmc.model.*;
import com.dmc.service.DistributionService;
import com.dmc.service.UserAccountService;
import com.dmc.service.UserService;
import com.dmc.util.AppConst;
import com.dmc.util.DecimalUtil;
import com.dmc.util.id.IdUtil;
import com.dmc.util.util.*;
import com.dmc.vo.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.base.Strings;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private TMsgCodeMapper tMsgCodeMapper;

    @Autowired
    private TUserAccountMapper tUserAccountMapper;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private CashOutOrdersMapper cashOutOrdersMapper;

    @Autowired
    private DistributionOrderMapper distributionOrderMapper;


    @Autowired
    private DistributionOrderQueueMapper distributionOrderQueueMapper;

    @Autowired
    private IntegralTransactionMapper integralTransactionMapper;

    @Autowired
    private BenefitTransactionMapper benefitTransactionMapper;

    @Autowired
    private DistributionShareRelationMapper distributionShareRelationMapper;

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private SysConfigMapper sysConfigMapper;

    @Autowired
    private VipConfigMapper vipConfigMapper;

    @Autowired
    private UserAccountService userAccountService;

    @Autowired
    private DistributionService distributionService;

    @Autowired
    private AchievementBonusConfigDetailMapper achievementBonusConfigDetailMapper;

    @Autowired
    private AchievementBonusConfigMapper achievementBonusConfigMapper;


    @Override
    public User login(User user) {
        Map<String, Object> params = new HashMap<>();
        params.put("username", user.getUsername());
        params.put("password", DigestUtils.md5Hex(user.getPassword()));
        user = userMapper.login(params);
        return user;
    }


    @Override
    public void add(User user) {
        user.setId(IdUtil.generateId());
        user.setShareRewardsHave(0);
        user.setLevel(0);
        user.setType(0);
        user.setShareGoodsRewardsHave(0);
        user.setStop(0);
        if (userMapper.countUserName(user.getUsername()) > 0) {
            throw new RuntimeException("登录名已存在！");
        } else {
            user.setPassword(DigestUtils.md5Hex(user.getPassword()));
            userMapper.save(user);
        }
    }

    @Override
    public void addUser(User user) {
        user.setPassword(DigestUtils.md5Hex(user.getPassword()));
        userMapper.save(user);
    }

    @Override
    public User get(Long id) {
        User user = userMapper.getById(id);
        if (user != null) {
            user.setRoleIds(userMapper.getUserRoleIds(id));
        }
        return user;
    }

    @Override
    public void edit(User user) {
        if (userMapper.countUserName(user.getName()) > 0) {
            throw new RuntimeException("登录名已存在！");
        } else {
            if (!Strings.isNullOrEmpty(user.getPassword())) {
                user.setPassword(DigestUtils.md5Hex(user.getPassword()));
            }
            //查询当前用户
            Long id = user.getId();
            Assert.notNull(id,"参数错误,无用户给ID");
            User byId = userMapper.getById(id);
            Assert.notNull(byId,"参数错误,无此用户");
            BeanUtil.copyProperties(user,byId, CopyOptions.create().setIgnoreNullValue(true));
            userMapper.update(byId);
        }
    }

    @Override
    public void delete(Long id) {
        userMapper.deleteRoles(id);
        userMapper.deleteById(id);
    }

    @Override
    public void grant(User user) {
        Assert.notNull(user.getId(), "id 不能为空");
        Assert.notEmpty(user.getRoleIds(), "roleIds must have length; it must not be null or empty");


        userMapper.deleteRoles(user.getId());
        userMapper.saveRoles(user.getId(), user.getRoleIds());
    }

    @Override
    public List<String> resourceList(Long id) {
        Map<String, Object> params = new HashMap<>();
        params.put("userId", id);
        params.put("type", AppConst.RESOURCE_TYPE_METHOD);
        List<Resource> resources = resourceMapper.getResourceList(params);
        return resources.stream().map(resource -> resource.getUrl() + "-" + resource.getMethod()).collect(Collectors.toList());
    }

    @Override
    public void editPwd(User user) {
        Assert.notNull(user, "user can not be null");
        Assert.notBlank(user.getPassword(), "password mush have value");

        user.setPassword(DigestUtils.md5Hex(user.getPassword()));
        userMapper.update(user);


    }

    @Override
    public boolean editCurrentUserPwd(Long currUid, String oldPwd, String pwd) {
        User user = userMapper.getById(currUid);
        if (user.getPassword().equalsIgnoreCase(DigestUtils.md5Hex(oldPwd))) {// 说明原密码输入正确
            user.setPassword(DigestUtils.md5Hex(pwd));
            userMapper.update(user);
            return true;
        }
        return false;
    }

    @Override
    public List<String> getUserRoleNames(Long id) {
        return userMapper.getUserRoleNames(id);
    }

    @Override
    public User getUserByOpenId(String openId) {
        return userMapper.getUserByOpenId(openId);
    }

    @Override
    public User getUserByPhone(String phone) {
        User userByPhone = userMapper.getUserByPhone(phone);
        Assert.notNull(userByPhone,"请核对手机号,无此用户");
        return userByPhone;
    }

    @Override
    public User getUserByWxPhone(String wxPhone) {
        return userMapper.getUserByWxPhone(wxPhone);
    }

    @Override
    public DataTable<User> tables(UserVO userVO) {
        PageHelper.offsetPage(userVO.getStart(), userVO.getLength());

        List<User> users = userMapper.findUser(new HashMap<>());
        DataTable<User> tables = new DataTable<>();
        tables.setRecordsTotal(((Page) users).getTotal());
        tables.setRecordsFiltered(tables.getRecordsTotal());
        tables.setDraw(userVO.getDraw());
        tables.setData(users);
        return tables;
    }

    @Override
    public String sendMsgCode(String phone,Integer type) {
        //先查看有没有有效的验证码
        long currentTime = System.currentTimeMillis();
        long validTimeLong = currentTime - SendSmsUtil.STOP_TIME;
        Date validTime = new Date(validTimeLong);
        MsgCode code = userMapper.getMsgCodeByTime(validTime);
        Assert.isNull(code,"您的验证码在有效期中,请勿重新发送");
        //如果没有发送新的验证码
        String msgCode = CreateCodeUtil.GetBindNum();
        SendSmsUtil.sendsms(phone,msgCode);
        //保存code
        code = new MsgCode();
        code.setId(IdUtil.generateId());
        code.setCode(msgCode);
        code.setCreateTime(new Date());
        code.setPhone(phone);
        code.setId(IdUtil.generateId());
        code.setStop(0);
        code.setType(type);
        tMsgCodeMapper.insert(code);
        return msgCode;
    }

    @Override
    public String checkMsgCode(String phone, String code,Integer type) {
        if(StringUtils.isNotBlank(code) && code.length() == 5){
            code = '0'+code;
        }
        //查询验证码是否在有效期
        MsgCode msgCode = userMapper.getMsgCodeByPhoneAndCode(phone,code,type);
        Assert.notNull(msgCode,"验证码错误");
        //校验是否已经过期
        Date createTime = msgCode.getCreateTime();
        Assert.isTrue(createTime !=null && (createTime.getTime()+SendSmsUtil.STOP_TIME)>System.currentTimeMillis(),"验证码已失效");
        Integer stop = msgCode.getStop();
        Assert.isTrue(stop == null || stop == 0,"验证码已失效");
        //将此手机号验证码置为已失效
        msgCode.setStop(1);
        tMsgCodeMapper.update(msgCode,null);
        return msgCode.getCode();
    }

    @Override
    public void bindPhone(String phone) {
        String oldData = "19133691626,13911884360,18831449676,15003242077,13613141388,13731404398,15131691315,13363146476,15076920018,17631469653,13931406268,18832408883,13831491598,17832443333,13932499032,18031412272,18322347722,13463678032,13910971928,13091359676,18832458591,13716752836,13810259621,13601117569,17600282411,13801024360,13264083768,13910271603,15233338582,13831454967,15531481828,13701217351,15932410909,13371730819,16619854975,17343273546,13253177248,15833240817,18803241266,15029584662,13520426430,15721968268,19945225656,13359136933,13717648593,15501020257,18919170200,19932374131,13343381833,18713421309,13403143362,18131458306,13091339686,15832401835,13931415676,13833404543,15503041119,18832420598,13191637686,15133807374,18631444166,18244550220,13516220725,13716071219,15732469997,15176757675,15031630359";
        //根据手机号查询,当前手机号是否绑定用户
        User userByPhone = userMapper.getUserByPhone(phone);
        Long currUid = SessionUtil.getCurrUid();
        User byId = userMapper.getById(currUid);
        if(!oldData.contains(phone)){
            Assert.isNull(userByPhone,"当前手机号已经被绑定");
        }else{
            new Thread(()->{
                mergeAccount(userByPhone,byId,phone);
            }).start();
            throw new IllegalArgumentException("已合并完您之前的数据,请重新登陆");
        }
        byId.setWxPhone(phone);
        byId.setUserPhone(phone);
        userMapper.update(byId);
    }

    /**
     * 老数据导入的用户,和新用户进行合并
     */
    public void mergeAccount(User oldUser,User newUser,String phone){
        Long newId = newUser.getId();
        Long oldId = oldUser.getId();
        Integer level = oldUser.getLevel();
        Long shareUserId = oldUser.getShareUserId();
        Integer shareGoodsRewardsHave = oldUser.getShareGoodsRewardsHave();
        Integer shareRewardsHave = oldUser.getShareRewardsHave();
        //合并到老用户
        BeanUtils.copyProperties(newUser,oldUser);
        oldUser.setShareUserId(shareUserId);
        oldUser.setShareGoodsRewardsHave(shareGoodsRewardsHave);
        oldUser.setShareRewardsHave(shareRewardsHave);
        oldUser.setLevel(level);
        oldUser.setId(oldId);
        oldUser.setWxPhone(phone);
        oldUser.setUserPhone(phone);
        userMapper.update(oldUser);
        //删除老用户
        userMapper.deleteById(newId);
        //删除之前登陆生成用户相关信息
        Map<String,Object> param = new HashMap<>();
        param.put("share_user_id",newId);
        distributionShareRelationMapper.deleteByMap(param);
        param = new HashMap<>();
        param.put("user_id",newId);
        tUserAccountMapper.deleteByMap(param);
    }


    @Override
    public UserCenterInfoVO getUserCenterInfo(Long currUid) {
        UserCenterInfoVO userCenterInfoVO = new UserCenterInfoVO();
        //获取用户信息
        User user = userMapper.getUserById(currUid);
        BeanUtil.copyProperties(user,userCenterInfoVO);
        Map<String,Object> param = new HashMap<>();
        param.put("user_id",currUid);
        List<TUserAccount> tUserAccounts = tUserAccountMapper.selectByMap(param);
        if(!CollectionUtil.isEmpty(tUserAccounts)){
            TUserAccount tUserAccount = tUserAccounts.get(0);
            userCenterInfoVO.setBenefit(tUserAccount.getBenefit());
            userCenterInfoVO.setIntegral(tUserAccount.getIntegral());
        }else{
            userCenterInfoVO.setBenefit(BigDecimal.ZERO);
            userCenterInfoVO.setIntegral(BigDecimal.ZERO);
        }
        Integer level = user.getLevel();
        Integer vipLevel = user.getVipLevel();
        String  levelName = UserLevelDict.getDescByCn(level);
        if(vipLevel!=null){
            VipConfig config = new VipConfig();
            config.setLevel(vipLevel);
            config.setStatus(0);
            VipConfig vipConfig = vipConfigMapper.selectOne(config);
            if(vipConfig!=null){
                levelName = levelName+"("+vipConfig.getVipName()+")";
            }
        }
        userCenterInfoVO.setLevelName(levelName);
        //订单相关数据
        Integer allOrderNum=ordersMapper.getTotalUserOrder(currUid,null);
        userCenterInfoVO.setAllOrderNum(allOrderNum);
        List<Long> orderStatusList = new ArrayList<>();
        orderStatusList.add(OrderStatusDict.ORDER_STATUS_SUCCESS.getCn());
        Integer closeOrderNum=ordersMapper.getTotalUserOrder(currUid, orderStatusList);
        userCenterInfoVO.setCloseOrderNum(closeOrderNum);
        orderStatusList.clear();
        orderStatusList.add(OrderStatusDict.ORDER_STATUS_CREATED.getCn());
        Integer readyPayOrderNum=ordersMapper.getTotalUserOrder(currUid,orderStatusList);
        userCenterInfoVO.setReadyPayOrderNum(readyPayOrderNum);
        orderStatusList.clear();
        orderStatusList.add(OrderStatusDict.ORDER_STATUS_PAIED.getCn());
        orderStatusList.add(OrderStatusDict.ORDER_STATUS_DELIVERY.getCn());
        Integer readyReciveOrderNum=ordersMapper.getTotalUserOrder(currUid,orderStatusList);
        userCenterInfoVO.setReadyReciveOrderNum(readyReciveOrderNum);
        //获取分销订单数量
        Integer distributionOrderNum = distributionOrderMapper.getOrderNumByUserId(currUid, null);
        userCenterInfoVO.setDistributionNum(distributionOrderNum == null?0:distributionOrderNum);
        Integer distributionPackOrderNum = distributionOrderMapper.getOrderPackNumByUserId(currUid, null);
        userCenterInfoVO.setDistributionPackNum(distributionPackOrderNum == null?0:distributionPackOrderNum);
        //获取未读消息数量
        param = new HashMap<>();
        param.put("user_id",currUid);
        param.put("status",0);
        List<Message> messageList=messageMapper.selectByMap(param);
        userCenterInfoVO.setUnMessageNum(messageList == null?0:messageList.size());
        //校验是否享受提成
        int sharenumOne = userMapper.getDistributionShareNum(currUid);
        if(user.getLevel()!=null && user.getLevel()>1 && sharenumOne>=3){
            String firstLevelFlag = user.getFirstLevelFlag();
            AchievementBonusConfig achievementBonusConfig =  achievementBonusConfigMapper.selectByFirstLevelFlag(firstLevelFlag);
            if(achievementBonusConfig!=null){
                BigDecimal achievementLimit = achievementBonusConfig.getAchievementLimit();
                BigDecimal distributionTotalPrice = user.getDistributionTotalPrice();
                Integer generations = achievementBonusConfig.getGenerations();
                generations = generations == null?0:generations;
                distributionTotalPrice = distributionService.getNextAchievement(currUid, distributionTotalPrice,generations);
                if(distributionTotalPrice.compareTo(achievementLimit)>=0){
                    userCenterInfoVO.setHaveBouns(1);
                }
            }
        }

        return userCenterInfoVO;
    }


    @Override
    public void updateUserWx(User u) {
        Long id = u.getId();
        if(id == null){
            id = SessionUtil.getCurrUid();
            u.setId(id);
        }
        User byId = userMapper.getById(id);
        Assert.notNull(byId,"修改失败,无此用户信息");
        byId.setAge(u.getAge());
        byId.setBirthday(u.getBirthday());
        byId.setName(u.getName());
        byId.setUserPhone(u.getUserPhone());
        String encryptedData = u.getEncryptedData();
        if(StringUtils.isNotBlank(encryptedData)){
            String iv = u.getIv();
            JSONObject openIdObject = WXBizDataCrypt.getOpenId(u.getCode(), iv);
            Assert.notNull(openIdObject,"登录失败,获取opendId失败");
            String openId = openIdObject.getString("openid");
            Assert.isTrue(StringUtils.isNotBlank(openId),"登录失败,无openId");
            //获取微信session_key密钥
            String sessionKey = openIdObject.getString("session_key");
            String userinfo= WXBizDataCrypt.decrypt1(u.getEncryptedData(),sessionKey,iv);
            if(StringUtils.isNotBlank(userinfo)){
                JSONObject jsonObject = JSON.parseObject(userinfo);
                byId.setUserPhoto(jsonObject.getString("avatarUrl"));
            }
        }
        userMapper.update(byId);
    }

    @Override
    public DataTable<UserInfoVO> getUserList(UserInfoVO vo) {
        Integer level = vo.getLevel();
        if(level!=null && level == 5){
            vo.setLevel(null);
        }
        Integer start = vo.getStart();
        if(start == null){
            vo.setStart(0);
        }
        Integer length = vo.getLength();
        if(length == null){
            vo.setLength(10);
        }
        String userName = vo.getName();
        if(StringUtils.isNotBlank(userName)){
            vo.setName("%"+userName.trim()+"%");
        }
        String userPhone = vo.getUserPhone();
        if(StringUtils.isNotBlank(userPhone)){
            vo.setUserPhone("%"+userPhone.trim()+"%");
        }
        vo.setType(1);
        PageHelper.startPage(vo.getStart(), vo.getLength());
        List<UserInfoVO> list = userMapper.getUserList(vo);
        if(!CollectionUtils.isEmpty(list)){
            for (UserInfoVO userInfoVO : list) {
                Integer auth = userInfoVO.getAuth();
                userInfoVO.setAuth(auth == null?0:auth);
                Integer stop = userInfoVO.getStop();
                userInfoVO.setStop(stop == null?0:stop);
                //获取提现的金额
                BigDecimal cashOutPrice = cashOutOrdersMapper.getCashOutPriceByUserId(userInfoVO.getId());
                userInfoVO.setCashOut(cashOutPrice);
                userInfoVO.setBenefitAll(DecimalUtil.addArray(cashOutPrice,userInfoVO.getBenefit()));
                //获取推荐人个数
                int sharenumOne = userMapper.getShareNum(userInfoVO.getId(),1);
                int sharenumTwo = userMapper.getShareNum(userInfoVO.getId(),2);
                userInfoVO.setShareNum(sharenumOne);
                //获取一级分销人数
                userInfoVO.setLevelOneOrderNum(sharenumOne);
                //获取二级分销人数
                userInfoVO.setLevelTwoOrderNum(sharenumTwo);
            }
        }
        DataTable<UserInfoVO> tables = new DataTable<>();
        tables.setRecordsTotal(((Page) list).getTotal());
        tables.setRecordsFiltered(tables.getRecordsTotal());
        tables.setDraw(vo.getDraw());
        tables.setData(list);
        return tables;
    }

    @Override
    public void sendMsg(QueryBaseVo queryBaseVo) {
        SendSmsUtil.sendsms(queryBaseVo.getPhone(),queryBaseVo.getMsg());
    }

    @Override
    public void closeUser(UserVO vo) {
        Long userId = vo.getId();
        Assert.notNull(userId,"参数错误,无此用户");
        User byId = userMapper.getUserById(userId);
        Assert.notNull(byId,"参数错误,无此用户");
        Integer stop = vo.getStop();
        stop = stop == null?0:stop;
        Integer stopOld = byId.getStop();
        stopOld = stopOld == null?0:stopOld;
        if(stop == stopOld){
            String msg = stop == 0?"无法启用,已经是启用状态":"无法禁用,已经是禁用状态";
            throw new IllegalArgumentException(msg);
        }else{
            if(stop == 0){
                byId.setOpenDes(vo.getOpenDes());
                byId.setOpenTime(new Date());
            }else{
                byId.setStopDes(vo.getStopDes());
                byId.setStopTime(new Date());
            }
            byId.setStop(stop);
            userMapper.update(byId);
        }
    }

    @Override
    public UserDisCountVo getDisCount(Long currUid) {
        UserDisCountVo vco = new UserDisCountVo();
        User byId = userMapper.getById(currUid);
        Assert.notNull(byId,"参数错误,无此用户");
        vco.setLevel(byId.getLevel());
        String value = null;
        if(byId.getLevel()!=null && byId.getLevel()>0){
            SysConfig config = new SysConfig();
            config.setConfigKey(Constant.CONFIG_KEY_GOOS_DISCOUNT_RATE);
            config = sysConfigMapper.selectOne(config);
            if(config!=null){
                value = config.getConfigValue();
            }
        }
        vco.setDiscountRate(value == null?"10":value);
        return vco;
    }

    @Override
    public List<VipConfigVo> getVipConfigList(Integer status) {
        List<VipConfigVo> result = new ArrayList<>();
        Map<String,Object> param = new HashMap<>();
        if(status!=null){
            param.put("status",0);
        }
        param.put("deleted",0);
        List<VipConfig> vipConfigs = vipConfigMapper.selectByMap(param);
        if(CollectionUtil.isEmpty(vipConfigs)){
            return result;
        }
        for (VipConfig vipConfig : vipConfigs) {
            VipConfigVo vo = new VipConfigVo();
            BeanUtil.copyProperties(vipConfig,vo);
            result.add(vo);
        }
        return result;
    }

    @Override
    public void addVipConfig(VipConfigVo vo) {
        checkVipConfig(vo);
        Long configId  = IdUtil.generateId();
        vo.setId(configId);
        VipConfig vipConfig = new VipConfig();
        BeanUtil.copyProperties(vo,vipConfig, CopyOptions.create().setIgnoreNullValue(true));
        vipConfigMapper.insert(vipConfig);
    }

    /**
     * 添加或者修改会员身份校验
     * @param vo
     */
    private void checkVipConfig(VipConfigVo vo){
        Long id = vo.getId();
        boolean isSave = id == null;
        Map<String,Object> params = new HashMap<>();
        params.put("vip_name",vo.getVipName());
        params.put("status",0);
        List<VipConfig> configList = vipConfigMapper.selectByMap(params);
        if(isSave){
            Assert.isTrue(CollectionUtils.isEmpty(configList),isSave?"添加":"更新"+"失败,已有同名会员身份");
        }else{
            if(CollectionUtil.isNotEmpty(configList)){
                for (VipConfig vipConfig : configList) {
                    Long nameId = vipConfig.getId();
                    Assert.isTrue(nameId.equals(id),isSave?"添加":"更新"+"失败,已有同名会员身份");
                }
            }
        }
        params.clear();
        params.put("level",vo.getLevel());
        params.put("status",0);
        configList = vipConfigMapper.selectByMap(params);
        if(isSave){
            Assert.isTrue(CollectionUtils.isEmpty(configList),isSave?"添加":"更新"+"失败,已有同级别会员身份");
        }else{
            if(CollectionUtil.isNotEmpty(configList)){
                for (VipConfig vipConfig : configList) {
                    Long nameId = vipConfig.getId();
                    Assert.isTrue(nameId.equals(id),isSave?"添加":"更新"+"失败,已有同级别会员身份");
                }
            }
        }
    }

    @Override
    public void updateVipConfig(VipConfigVo vo) {
        Assert.notNull(vo.getId(),"更新失败,无会员身份ID");
        VipConfig vipConfig = vipConfigMapper.selectById(vo.getId());
        Assert.notNull(vipConfig,"更新失败,无此会员身份");
        checkVipConfig(vo);
        BeanUtil.copyProperties(vo,vipConfig, CopyOptions.create().setIgnoreNullValue(true));
        vipConfigMapper.updateById(vipConfig);
    }

    @Override
    public void transferProfit(TransferProfitVo vo) {
        String userPhone = vo.getUserPhone();
        Assert.notNull(userPhone,"转账失败,被转账人手机号不可为空");
        BigDecimal transferPrice = vo.getTransferPrice();
        Assert.isTrue(transferPrice!=null && transferPrice.compareTo(BigDecimal.ZERO)>0,"转账失败,金额不可为空");
        User userByPhone = userMapper.getUserByPhone(userPhone);
        Assert.notNull(userByPhone,"转账失败,无此被转账人");
        Integer level = userByPhone.getLevel();
        Assert.isTrue(level!=null && level>0,"被转账人非会员,无法转账");
        Long currUid = SessionUtil.getCurrUid();
        User currUser = userMapper.getById(currUid);
        Long otherUserId = userByPhone.getId();
        //更新转账人
        TUserAccount userAccount = userAccountService.initUserAccountByUserId(currUid);
        BigDecimal benefit = userAccount.getBenefit();
        BigDecimal benefitBanlace = DecimalUtil.subArrayOriginalValue(benefit, transferPrice);
        Assert.isTrue(benefitBanlace.compareTo(BigDecimal.ZERO)>=0,"账户金额,不足以转账");
        userAccount.setBenefit(benefitBanlace);
        tUserAccountMapper.updateById(userAccount);
        //更新被转账人
        TUserAccount userAccountTransfer = userAccountService.initUserAccountByUserId(otherUserId);
        BigDecimal benefitTransfer = userAccountTransfer.getBenefit();
        BigDecimal benefitTransferNew = DecimalUtil.addArray(benefitTransfer, transferPrice);
        userAccountTransfer.setBenefit(benefitTransferNew);
        tUserAccountMapper.updateById(userAccountTransfer);
        //添加记录
        BenefitTransaction bt = new BenefitTransaction( currUid,otherUserId,null,benefitBanlace,
                BenefitTranTypeDict.BENEFIT_TRAN_TYPE_600.getCn(),  transferPrice.negate(), "转账给"+userByPhone.getName()+",收益减少");
        userAccountService.addBenefitTransaction(bt);
        BenefitTransaction btOther = new BenefitTransaction( otherUserId,currUid,null,benefitTransferNew,
                BenefitTranTypeDict.BENEFIT_TRAN_TYPE_700.getCn(),  transferPrice, "被"+currUser.getName()+"转账,收益增加");
        userAccountService.addBenefitTransaction(btOther);
    }

    @Override
    public void uddateSharePhone(Long id, String shareUserPhone) {
        User byId = userMapper.getById(id);
        Assert.notNull(byId,"无此用户");
        User userByPhone = userMapper.getUserByPhone(shareUserPhone);
        Assert.notNull(userByPhone,"请查验手机号,无此推荐人");
        byId.setShareUserId(userByPhone.getId());
        userMapper.updateById(byId);
        DistributionShareRelation relation = new DistributionShareRelation();
        relation.setUserId(id);
        relation = distributionShareRelationMapper.selectOne(relation);
        if(relation==null){
            relation = new DistributionShareRelation();
            relation.setCreateTime(new Date());
            relation.setUserId(byId.getId());
            relation.setShareUserId(byId.getShareUserId());
            relation.setOrderId(null);
            distributionService.insertRelation(relation);
        }else{
            relation.setShareUserId(byId.getShareUserId());
            relation.setUpdateTime(new Date());
            distributionShareRelationMapper.updateById(relation);
        }
    }

}
